use sqlx::{MySqlConnection, Connection};
use std::fs;
use std::path::Path;

pub async fn img_2_db(conn_url: &str, file_path: &str) {
    let mut conn = MySqlConnection::
    connect(conn_url).await.unwrap();
    println!("  -- connected");
    let v = read_file(file_path);
    for info in v {
        println!("  -- insert into database : {}", info.user_name);
        run_insert(&mut conn, info).await;
    }
}

async fn run_insert(conn: &mut MySqlConnection, info: Info) {
    let sql = format!("insert into tmp_table (name,img,id,identity) values (\"{}\",\"{}\",{},\"{}\")",
                      info.user_name, info.img, info.user_id, info.user_identity);
    let result = sqlx::query(&sql).fetch_one(conn).await;
    match result {
        Ok(row) => { println!("row: {:?}", row) }
        // insert end and return null row is no problem
        Err(e) => { println!("err: {:?}", e) }
    }
}

#[derive(Debug)]
struct Info {
    user_name: String,
    user_identity: String,
    user_id: String,
    img: String,
}

fn read_file(path_str: &str) -> Vec<Info> {
    let path = Path::new(path_str);
    let regex = regex::Regex::new(r"(.+)_(\w+)#(\d+)").unwrap();
    let mut v = Vec::<Info>::new();
    if path.is_file() {
        if let Some(name_os) = path.file_name() {
            if let Some(name) = name_os.to_str() {
                for c in regex.captures_iter(name) {
                    let img_base64 = base64::encode(fs::read(path).unwrap());
                    let info = Info {
                        user_name: c.get(1).unwrap().as_str().to_string(),
                        user_identity: c.get(2).unwrap().as_str().to_string(),
                        img: String::from("data:image/png;base64,") + img_base64.as_str(),
                        user_id: c.get(3).unwrap().as_str().to_string(),
                    };
                    println!("  -- save info name : {}", info.user_name);
                    v.push(info);
                }
            }
        }
    } else if path.is_dir() {
        let dirs = fs::read_dir(path).unwrap();
        for de in dirs {
            if let Some(s) = de.unwrap().path().to_str() {
                v.append(&mut read_file(s))
            };
        }
    } else { println!(" -- continue path cause unknown : {}", &path_str); }
    v
}